package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类,定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 定时处理超时未支付的订单
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟的0秒执行
    public void processTimeoutOrder(){
        log.info("定时处理超时未支付的订单：{}", LocalDateTime.now());
        //查询出超时未支付的订单 select * from orders where status = 未支付 and order_time < 当前时间减去15
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,LocalDateTime.now().minusMinutes(15));
        if(ordersList != null && ordersList.size() > 0){
            //设置取消的属性 并且更新数据库
            for (Orders orders : ordersList) {
                Orders o = new Orders();
                o.setId(orders.getId());
                o.setCancelReason("订单超时未支付，自动取消");
                o.setCancelTime(LocalDateTime.now());
                o.setStatus(Orders.CANCELLED);
                orderMapper.update(o);
            }
        }
    }

    /**
     * 定时处理一直在派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("定时处理一直在派送中的订单:{}",LocalDateTime.now());
        //获取前一天的一直在派送的订单 也就是0点以前的订单
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS,time);
        if(ordersList != null && ordersList.size() > 0){
            //设置完成的属性 并且更新数据库
            for (Orders orders : ordersList) {
                Orders o = new Orders();
                o.setId(orders.getId());
                o.setStatus(Orders.COMPLETED);
                orderMapper.update(o);
            }
        }
    }
}
